#include "Huffman.h"

void Huffman::buildTree(GLinkedList<HNode<WordOcurrence> >& ocurrences)
{
    while (ocurrences.size() != 1)
    {
        HNode<WordOcurrence> first;
        ocurrences.remove(0, first);
        HNode<WordOcurrence> second;
        ocurrences.remove(0, second);
        WordOcurrence parentReference(' ', first.getValue().getAmount() + second.getValue().getAmount());
        HNode<WordOcurrence> parent(parentReference);
        parent.setLeft(first.getValue());
        parent.setRight(second.getValue());
        ocurrences.addSort(parent);
    }
}

void Huffman::countOcurrence(const char* str, GLinkedList<HNode<WordOcurrence> > & ocurrences)
{
    for (int i = 0; i < strlen(str); i++)
    {
        WordOcurrence ocurrence(str[i], 1);
        HNode<WordOcurrence> node(ocurrence);
        try
        {
            ocurrences.find(node).getValue()++;
        } catch (...)
        {
            ocurrences.addSort(node);
        }
    }
}